#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This is the future implementaion of GoWrapper, not recommended to use.

import sys,os,glob
sys.path += glob.glob(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..\goagent-local\python*.zip'))
sys.path += glob.glob(os.path.dirname(os.path.abspath(__file__)))
sys.path += glob.glob(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'python*'))
import sip,time,subprocess,psutil,ctypes,_winreg
sip.setapi('QVariant', 2)
from PyQt4 import QtCore, QtGui
from threading import Thread
import gowrapper_rc

# GoWrapper
class MainWindow(QtGui.QMainWindow):
	lineCount=0
	def __init__(self):
		super(MainWindow, self).__init__()
		self.curFile = ''
		self.textEdit = QtGui.QTextEdit()
		self.textEdit.setReadOnly(True)
		self.setCentralWidget(self.textEdit)
		self.createActions()
		self.createMenus()
		self.createToolBars()
		self.createStatusBar()
		self.readSettings()
		self.textEdit.document().contentsChanged.connect(self.documentWasModified)
		self.setCurrentFile('')
		self.setUnifiedTitleAndToolBarOnMac(True)

	def openURL(self,URL):
		pass
		
	def newFile(self):
		self.textEdit.clear()
		self.setCurrentFile('')

	def open(self):
		fileName = QtGui.QFileDialog.getOpenFileName(self)
		if fileName:
			self.loadFile(fileName)

	def save(self):
		if self.curFile:
			return self.saveFile(self.curFile)
		return self.saveAs()

	def saveAs(self):
		fileName = QtGui.QFileDialog.getSaveFileName(self)
		if fileName:
			return self.saveFile(fileName)
		return False

	def about(self):
		QtGui.QMessageBox.about(self, u"关於GoWrapper", u"<b>GoWrapper</b> 是一个很简单的GoAgent包装器，最适合不会设置PAC和代理的傻瓜(或懒人)使用")

	def documentWasModified(self):
		self.setWindowModified(self.textEdit.document().isModified())

	def createActions(self):
		#self.vjmediaAct = QtGui.QAction(QtGui.QIcon(':/resources/favicons/fb.png'), "Vjmedia",	self, statusTip="Vjmedia",triggered=self.open)	
		self.newAct = QtGui.QAction(QtGui.QIcon(':/resources/buttons/new.png'), "&New",self, shortcut=QtGui.QKeySequence.New,statusTip="Create a new file", triggered=self.newFile)
		self.openAct = QtGui.QAction(QtGui.QIcon(':/resources/buttons/open.png'),"&Open...", self, shortcut=QtGui.QKeySequence.Open,statusTip="Open an existing file", triggered=self.open)
		self.saveAct = QtGui.QAction(QtGui.QIcon(':/resources/buttons/save.png'),"&Save", self, shortcut=QtGui.QKeySequence.Save,statusTip="Save the document to disk", triggered=self.save)
		self.saveAsAct = QtGui.QAction("Save &As...", self,shortcut=QtGui.QKeySequence.SaveAs,statusTip="Save the document under a new name",triggered=self.saveAs)
		self.cleanAct = QtGui.QAction(u"修复退出(&F)", self, shortcut="Ctrl+F",statusTip=u"退出并清除PAC", triggered=self.clean)
		self.exitAct = QtGui.QAction(u"正常退出(&Q)", self, shortcut="Ctrl+Q",statusTip=u"退出并还原PAC", triggered=self.close)
		self.cutAct = QtGui.QAction(QtGui.QIcon(':/resources/buttons/cut.png'), "Cu&t",self, shortcut=QtGui.QKeySequence.Cut,statusTip="Cut the current selection's contents to the clipboard",triggered=self.textEdit.cut)
		self.copyAct = QtGui.QAction(QtGui.QIcon(':/resources/buttons/copy.png'),"&Copy", self, shortcut=QtGui.QKeySequence.Copy,statusTip="Copy the current selection's contents to the clipboard",triggered=self.textEdit.copy)
		self.pasteAct = QtGui.QAction(QtGui.QIcon(':/resources/buttons/paste.png'),"&Paste", self, shortcut=QtGui.QKeySequence.Paste,statusTip="Paste the clipboard's contents into the current selection",triggered=self.textEdit.paste)
		self.aboutAct = QtGui.QAction(u"关於(&A)", self,statusTip="Show the application's About box",triggered=self.about)
		self.cutAct.setEnabled(False)
		self.copyAct.setEnabled(False)
		self.textEdit.copyAvailable.connect(self.cutAct.setEnabled)
		self.textEdit.copyAvailable.connect(self.copyAct.setEnabled)

	def createMenus(self):
		self.fileMenu = self.menuBar().addMenu("&GoWrapper")
		self.fileMenu.addAction(self.newAct)
		self.fileMenu.addAction(self.openAct)
		self.fileMenu.addAction(self.saveAct)
		self.fileMenu.addAction(self.saveAsAct)
		self.fileMenu.addSeparator();
		self.fileMenu.addAction(self.cleanAct)
		self.fileMenu.addAction(self.exitAct)
		#self.editMenu = self.menuBar().addMenu("&Edit")
		#self.editMenu.addAction(self.cutAct)
		#self.editMenu.addAction(self.copyAct)
		#self.editMenu.addAction(self.pasteAct)
		#self.menuBar().addSeparator()
		self.helpMenu = self.menuBar().addMenu(u"帮助(&H)")
		self.helpMenu.addAction(self.aboutAct)

	def createToolBars(self):
		#self.fileToolBar = self.addToolBar("Link")
		#self.fileToolBar.addAction(self.vjmediaAct)
		self.fileToolBar = self.addToolBar("File")
		self.fileToolBar.addAction(self.newAct)
		self.fileToolBar.addAction(self.openAct)
		self.fileToolBar.addAction(self.saveAct)
		#self.editToolBar = self.addToolBar("Edit")
		#self.editToolBar.addAction(self.cutAct)
		#self.editToolBar.addAction(self.copyAct)
		#self.editToolBar.addAction(self.pasteAct)

	def createStatusBar(self):
		self.statusBar().showMessage("Ready")

	def readSettings(self):
		settings = QtCore.QSettings("Trolltech", "Application Example")
		pos = settings.value("pos", QtCore.QPoint(200, 200))
		size = settings.value("size", QtCore.QSize(400, 400))
		self.resize(size)
		self.move(pos)

	def writeSettings(self):
		settings = QtCore.QSettings("Trolltech", "Application Example")
		settings.setValue("pos", self.pos())
		settings.setValue("size", self.size())

	def loadFile(self, fileName):
		file = QtCore.QFile(fileName)
		if not file.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
			QtGui.QMessageBox.warning(self, "Application", "Cannot read file %s:\n%s." % (fileName, file.errorString()))
			return

		inf = QtCore.QTextStream(file)
		QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
		self.textEdit.setPlainText(inf.readAll())
		QtGui.QApplication.restoreOverrideCursor()
		self.setCurrentFile(fileName)
		self.statusBar().showMessage("File loaded", 2000)

	def saveFile(self, fileName):
		file = QtCore.QFile(fileName)
		if not file.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
			QtGui.QMessageBox.warning(self, "Application",
					"Cannot write file %s:\n%s." % (fileName, file.errorString()))
			return False
		outf = QtCore.QTextStream(file)
		QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
		outf << self.textEdit.toPlainText()
		QtGui.QApplication.restoreOverrideCursor()
		self.setCurrentFile(fileName);
		self.statusBar().showMessage("File saved", 2000)
		return True

	def setCurrentFile(self, fileName):
		self.curFile = fileName
		self.textEdit.document().setModified(False)
		self.setWindowModified(False)
		if self.curFile:
			shownName = self.strippedName(self.curFile)
		else:
			shownName = u'G翻墙'
		self.setWindowTitle("%s - GoWrapper" % shownName)

	def strippedName(self, fullFileName):
		return QtCore.QFileInfo(fullFileName).fileName()

	def closeEvent(self, event):
		self.writeSettings()
		self.statusBar().showMessage(u"正在还原PAC...")
		hkey = _winreg.OpenKey(HKEY_CURRENT_USER, SUB_KEY_PATH, 0, _winreg.KEY_ALL_ACCESS)	
		if originalpac != "":
			_winreg.SetValueEx(hkey, 'AutoConfigURL', 0,  _winreg.REG_SZ, originalpac)
		else:
			result=subprocess.check_output('reg delete "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v AutoConfigURL /f',stderr=subprocess.STDOUT)
		updateinternetoption()
		self.statusBar().showMessage(u"正在关闭GoAgent子程序...")
		self.selfkill()
		event.accept()

	def clean(self):
		global originalpac
		originalpac=""
		self.close()

	def goagentinit(self):
		thread = goagent()
		self.connect(thread, thread.signalAppend, self.signaltriggerAppend)
		self.connect(thread, thread.signalClean, self.signaltriggerClean)
		thread.start()

	def signaltriggerAppend(self, sigstr):
		self.textEdit.append(str(sigstr))
		self.textEdit.moveCursor(QtGui.QTextCursor.End)
		self.lineCount=self.lineCount+1
		
	def signaltriggerClean(self):
		tc = self.textEdit.textCursor()
		tc.movePosition( QtGui.QTextCursor.Start )
		tc.select( QtGui.QTextCursor.BlockUnderCursor )
		tc.removeSelectedText()
		tc.deleteChar()
		self.textEdit.moveCursor(QtGui.QTextCursor.End)

	def selfkill(self):
		parent = psutil.Process(os.getpid())
		for child in parent.get_children(recursive=True):
			child.kill()
		parent.kill()


class goagent(QtCore.QThread):
	def __init__(self):
		QtCore.QThread.__init__(self, parent=app)
		self.signalAppend = QtCore.SIGNAL("signalAppend")
		self.signalClean = QtCore.SIGNAL("signalClean")

	def run(self):
		startupinfo = subprocess.STARTUPINFO()
		startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
		lineCount = 0
		cmd = subprocess.Popen(["..\goagent-local\python27.exe","..\goagent-local\proxy.py"], startupinfo=startupinfo, stdout=subprocess.PIPE)# Need redirect stderr to stdout
		while(1):
			line = cmd.stdout.readline()
			self.emit(self.signalAppend, line.replace("\r\n",""))
			lineCount=lineCount+1
			if lineCount  > 1000:
				self.emit(self.signalClean)

def updateinternetoption():
	INTERNET_OPTION_SETTINGS_CHANGED = 39 # INTERNET_OPTION_REFRESH = 37
	Wininet = ctypes.windll.Wininet
	InternetSetOption = Wininet.InternetSetOptionW
	InternetSetOption(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0) # InternetSetOption(0, INTERNET_OPTION_REFRESH, 0, 0)

if __name__ == '__main__':
	HKEY_CURRENT_USER = _winreg.HKEY_CURRENT_USER
	SUB_KEY_PATH = r'Software\Microsoft\Windows\CurrentVersion\Internet Settings'
	hkey = _winreg.OpenKeyEx(HKEY_CURRENT_USER, SUB_KEY_PATH, 0, _winreg.KEY_READ | _winreg.KEY_WRITE)
	try:
		(originalpac, _) = _winreg.QueryValueEx(hkey, 'AutoConfigURL')
	except:
		originalpac=""

	_winreg.SetValueEx(hkey, 'AutoConfigURL', 0, _winreg.REG_SZ, "http://127.0.0.1:8965/proxy.pac")
	updateinternetoption()

	app = QtGui.QApplication(sys.argv)
	app.setStyle("windowsxp")
	mainWin = MainWindow()
	mainWin.show()
	QtCore.QTimer.singleShot(0, mainWin.goagentinit)
	os.system('start "" "iexplore" "http://www.ifanqiang.com"')
	sys.exit(app.exec_())